package com.oracle.sbdb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.oracle.sbdb.bo.BugInfoBo;
import com.oracle.sbdb.servlet.model.BugInformation;
import com.oracle.sbdb.util.JSONUtility;

/**
 * Servlet implementation class SelectBugbyKeyPhrase
 */
@WebServlet("/selectBugbyKeyPhrase")
public class SelectBugbyKeyPhrase extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public SelectBugbyKeyPhrase() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String keyPhrase = request.getParameter("keyPhrase");
		String responseContent = selectBugbyKeyPhrase(keyPhrase);
		PrintWriter out = response.getWriter();
		out.write(responseContent);
		out.flush();
		out.close();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject requestJson = JSONUtility.getRequestString(request);
		String keyPhrase = requestJson.getString("keyPhrase");
		String responseContent = selectBugbyKeyPhrase(keyPhrase);
		PrintWriter out = response.getWriter();
		out.write(responseContent);
		out.flush();
		out.close();
	}

	private String selectBugbyKeyPhrase(String keyPhrase){
		List<BugInformation> bugList = null;
		try{
			if(keyPhrase != null){
				bugList = BugInfoBo.INSTANCE.selectbyKeyPhrase(keyPhrase);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		JSONObject res = new JSONObject();
		res.put("Status", bugList == null ? "Fail" : "Success");
		res.put("Result", bugList);
		return res.toString();
	}
}
